<?php

namespace app\admin\controller;

use app\admin\model\User;
use app\admin\model\user\Balance;
use app\common\controller\Backend;
use Carbon\Carbon;
use Carbon\Exceptions\Exception;
use think\Cache;
use think\Db;
use app\admin\model\Transaction;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Statistics extends Backend
{

    /**
     * Roomclose模型对象
     * @var \app\admin\model\Roomclose
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();

    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index()
    {
        $starttime = Carbon::now()->startOfMonth()->toDateTimeString();
        $endtime = Carbon::now()->endOfMonth()->toDateTimeString();


        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

            $stores = \app\admin\model\Store::all();

            //初始化
            $output = [];
            foreach ($stores as $v) {
                $output[$v->id] = [
                    'id' => $v->id,
                    'store_name' => $v->store_name,
                    'reserve_num' => 0,
                    'reserve_done_num' => 0,
                    'reserve_cancel_num' => 0,
                    'total_reserve_hours' => 0,
                    'total_reserve_fee' => 0,
                ];
            }

            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            $filter = $filter ? $filter : [];

            $reserve = new \app\admin\model\Reserve();

            if (isset($filter['statics_time'])) {
                list($starttime, $endtime) = explode(' - ', $filter['statics_time']);
            }
            $reserve->where('endtime', '>', $starttime)
                ->where('user_id', 'not in', [5077, 5079]) //去掉自己和涛哥
                ->where('endtime', '<', $endtime);

            $records = $reserve->select();


            if ($records) {
                $groupedArray = $this->array_group_by($records, 'store_id');
            } else {
                $groupedArray = [];
            }

            foreach ($groupedArray as $k => $storeData) {
                foreach ($storeData as $v) {
                    $output[$v->store_id]['reserve_num']++;
                    if (2 == $v->re_status) {
                        $output[$v->store_id]['reserve_cancel_num']++;
                    } else if (1 == $v->re_status) {
                        $output[$v->store_id]['reserve_done_num']++;
                        $output[$v->store_id]['total_reserve_hours'] += strtotime($v->endtime) - strtotime($v->starttime);
                    }
                }
            }

            $output = array_map(function ($e) {
                $e['total_reserve_hours'] = intval($e['total_reserve_hours'] / 3600);
                return $e;
            }, $output);

            $result = array("total" => count($output), "rows" => array_values($output));

            return json($result);
        }
        $this->view->assign('starttime', $starttime);
        $this->view->assign('endtime', $endtime);
        return $this->view->fetch();
    }

    public function storeRenttime()
    {
        $starttime = Carbon::now()->startOfMonth()->toDateTimeString();
        $endtime = Carbon::now()->endOfMonth()->toDateTimeString();

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        if ($this->request->isAjax()) {

            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            $filter = $filter ? $filter : [];

            $reserve = new \app\admin\model\Reserve();

            if (isset($filter['statics_time'])) {
                list($starttimeStr, $endtimeStr) = explode(' - ', $filter['statics_time']);
            }
            $data = $reserve->where('endtime', '>', $starttimeStr)
                ->where('user_id', 'not in', [5077, 5079]) //去掉自己和涛哥
                ->where('endtime', '<', $endtimeStr)
                ->where('store_id', $filter['store_id'])
                ->order('id', 'asc')
                ->select();

            $starttime = Carbon::parse($starttimeStr);
            $endtime = Carbon::parse($endtimeStr);

            $step = 0;
            if ('month' == $filter['period']) {
                $step = $starttime->diffInMonths($endtime);
            } else if ('week' == $filter['period']) {
                $step = $starttime->diffInWeeks($endtime);
            } else if ('day' == $filter['period']) {
                $step = $starttime->diffInDays($endtime);
            }

            $output = [];
            for ($i = 0; $i <= $step; $i++) {
                $s = $e = null;
                if ('month' == $filter['period']) {
                    $s = Carbon::parse($starttimeStr)->addMonths($i);
                    $e = Carbon::parse($starttimeStr)->addMonths($i+1);
                } else if ('week' == $filter['period']) {
                    $s = Carbon::parse($starttimeStr)->addWeeks($i);
                    $e = Carbon::parse($starttimeStr)->addWeeks($i+1);
                } else if ('day' == $filter['period']) {
                    $s = Carbon::parse($starttimeStr)->addDays($i);
                    $e = Carbon::parse($starttimeStr)->addDays($i+1);
                }

//                echo 'iiii=>' . $i . PHP_EOL;
//                echo $s->toDateTimeString() . '到' . $e->toDateTimeString() . '####';
                $reserveNum = $doneNum = $cancelNum = $reserveHour  = $doneHour = $cancelHour = 0;
                $payDirect = $payBalance = $payCard = $payDzmt = $payCombine = 0;
                $payDirectDone = $payBalanceDone = $payCardDone = $payDzmtDone = $payCombineDone= 0;
                $payDirectCancel = $payBalanceCancel = $payCardCancel = $payDzmtCancel = $payCombineCancel = 0;
                $allIncome = $directIncome = $balanceIncome = $cardIncome = $dzmtIncome = $cCardIncome = $cBalanceIncome = $cDirectIncome = 0;

                foreach ($data as $k => $item) {
                    $income = 0;
                    if (Carbon::parse($item->endtime)->betweenExcluded($s, $e)) {
                        $reserveNum++;
                        $reserveHour += strtotime($item->endtime) - strtotime($item->starttime);
                        if (2 == $item->re_status) {
                            $cancelNum++;
                            $cancelHour += strtotime($item->endtime) - strtotime($item->starttime);
                        } else if (1 == $item->re_status) {
                            $doneNum++;
                            $doneHour += strtotime($item->endtime) - strtotime($item->starttime);
                        }
                        if (1 == $item->pay_way) {
                            $card = \app\admin\model\user\Card::find($item->card_id);
                            if ($card) {
                                if (1 == $card->pay_way) {
                                    $payDzmt++;
                                    if (2 == $item->re_status) {
                                        $payDzmtCancel++;
                                    } else if (1 == $item->re_status) {
                                        $pricePerHour = ceil($card->price / $card->total_hour);
                                        $hour = floor(strtotime($item->endtime) - strtotime($item->starttime)) / 3600;
                                        $income = ceil($pricePerHour * $hour);
                                        $dzmtIncome += $income;
                                        $payDzmtDone++;
                                    }
                                } else if (2 == $card->pay_way) {
                                    $payCard++;
                                    if (2 == $item->re_status) {
                                        $payCardCancel++;
                                    } else if (1 == $item->re_status) {
                                        $pricePerHour = ceil($card->price / $card->total_hour);
                                        $hour = floor(strtotime($item->endtime) - strtotime($item->starttime)) / 3600;
                                        $income = ceil($pricePerHour * $hour);

                                        $cardIncome += $income;
                                        $payCardDone++;
                                    }
                                }
                            }
                        } else if (2 == $item->pay_way) {
                            $payBalance++;
                            if (2 == $item->re_status) {
                                $payBalanceCancel++;
                            } else if (1 == $item->re_status) {
                                $rate = (function ($userId) {
                                    if ($rate = Cache::get('rate-'.$userId)) {
                                        return $rate;
                                    } else {
                                        $countSum = 0;
                                        $countTotal = 0;
                                        $rechanges = \app\admin\model\Transaction::where('type', \app\admin\model\Transaction::TRANS_TYPE_RECHARGE)
                                            ->where('fa_transaction.status', 2)
                                            ->where('fa_transaction.user_id', $userId)
                                            ->select();
                                        foreach ($rechanges as $v) {
                                            $extraInfo = json_decode($v->extra_info, true);
                                            $countSum += $extraInfo['num'];
                                            $countTotal += $extraInfo['num'] + $extraInfo['extra'];
                                        }
                                        if (!$countTotal) {
                                            $rate = 1;
                                        } else {
                                            $rate  = round($countSum / $countTotal, 2);
                                        }
                                        Cache::set('rate-'. $userId, $rate, 3600);
                                        return $rate;
                                    }
                                })($item->user_id);
                                $income = ceil($item->fee * $rate);
                                $balanceIncome += $income;
                                $payBalanceDone++;
                            }
                        } else if (3 == $item->pay_way) {
                            $payDirect++;
                            if (2 == $item->re_status) {
                                $payDirectCancel++;
                            } else if (1 == $item->re_status) {
                                $income = $item->fee;
                                $directIncome += $item->fee;
                                $payDirectDone++;
                            }
                        } else if (5 == $item->pay_way) {
                            $cDirectPay = $cCardPay = $cBalancePay = 0;
                            $payCombine++;
                            if (2 == $item->re_status) {
                                $payCombineCancel++;
                            } else if (1 == $item->re_status) {
                                $payCombineDone++;

                                $cDirectPay = Transaction::get($item->transaction_id)->fee;
                                $cDirectIncome += $cDirectPay;
                                if (!is_null($item->card_id)) {
                                    $r = ($item->fee - $cDirectPay) / $item->fee;
                                    $card = \app\admin\model\user\Card::find($item->card_id);
                                    if ($card) {
                                        $pricePerHour = ceil($card->price / $card->total_hour);
                                        $hour = floor(strtotime($item->endtime) - strtotime($item->starttime)) / 3600 * $r;
                                        $cCardPay = ceil($pricePerHour * $hour);
                                        $cCardIncome += $cCardPay;
                                    }
                                }
                                if (!is_null($item->balance_id)) {
                                    $rate = (function ($userId) {
                                        if ($rate = Cache::get('rate-'.$userId)) {
                                            return $rate;
                                        } else {
                                            $countSum = 0;
                                            $countTotal = 0;
                                            $rechanges = \app\admin\model\Transaction::where('type', \app\admin\model\Transaction::TRANS_TYPE_RECHARGE)
                                                ->where('fa_transaction.status', 2)
                                                ->where('fa_transaction.user_id', $userId)
                                                ->select();
                                            foreach ($rechanges as $v) {
                                                $extraInfo = json_decode($v->extra_info, true);
                                                $countSum += $extraInfo['num'];
                                                $countTotal += $extraInfo['num'] + $extraInfo['extra'];
                                            }
                                            if (!$countTotal) {
                                                $rate = 1;
                                            } else {
                                                $rate  = round($countSum / $countTotal, 2);
                                            }
                                            Cache::set('rate-'. $userId, $rate, 3600);
                                            return $rate;
                                        }
                                    })($item->user_id);

                                    $cBalancePay = Balance::get($item->balance_id)->value;
                                    $cBalanceIncome += $cBalancePay;
                                }
                            }
                            $income = $cDirectPay + $cCardPay + $cBalancePay;
                        }

                        $allIncome += $income;

                        unset($data[$k]);
                    }
                }
                $key = '';
                if ('month' == $filter['period']) {
                    $key =  $s->format('Y-m');
                } else if ('week' == $filter['period']) {
                    $key =  $s->format('Y-m-d') . '('. $s->weekOfYear .')';
                } else if ('day' == $filter['period']) {
                    $key =  $s->format('Y-m-d') . '(周'. ($s->dayOfWeek == 0 ? '天' : $s->dayOfWeek) .')';
                }
                $output[] = [
                    'id' => $i,
                    'key' => $key,
                    'reserve_num' => $reserveNum,
                    'done_num' => $doneNum,
                    'cancel_num' => $cancelNum,
                    'reserve_hour' => intval($reserveHour / 3600),
                    'done_hour' => intval($doneHour / 3600),
                    'cancel_hour' => intval($cancelHour / 3600),
                    'pay_direct' => $payDirect,
                    'pay_balance' => $payBalance,
                    'pay_card' => $payCard,
                    'pay_dzmt' => $payDzmt,
                    'pay_direct_done' => $payDirectDone,
                    'pay_balance_done' => $payBalanceDone,
                    'pay_card_done' => $payCardDone,
                    'pay_dzmt_done' => $payDzmtDone,
                    'pay_direct_cancel' => $payDirectCancel,
                    'pay_balance_cancel' => $payBalanceCancel,
                    'pay_card_cancel' => $payCardCancel,
                    'pay_dzmt_cancel' => $payDzmtCancel,
                    'all_income' => $allIncome,
                    'direct_income' => $directIncome,
                    'balance_income' => $balanceIncome,
                    'card_income' => $cardIncome,
                    'dzmt_income' => $dzmtIncome,

                    'pay_combine' => $payCombine,
                    'pay_combine_done' => $payCombineDone,
                    'pay_combile_cancel' => $payCombineCancel,
                    'combine_card_income' => $cCardIncome,
                    'combine_balance_income' => $cBalanceIncome,
                    'combine_direct_income' => $cDirectIncome,
                ];
            }

            $result = array("total" => count($output), "rows" => $output);

            return json($result);
        }

        $stores = \app\admin\model\Store::all();

        $this->view->assign('stores', $stores);
        $this->view->assign('starttime', $starttime);
        $this->view->assign('endtime', $endtime);

        return $this->view->fetch();

    }

    public function storeWeekDistribution()
    {
        $starttime = Carbon::now()->startOfMonth()->toDateTimeString();
        $endtime = Carbon::now()->endOfMonth()->toDateTimeString();

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        if ($this->request->isAjax()) {

            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            $filter = $filter ? $filter : [];

            $reserve = new \app\admin\model\Reserve();

            if (isset($filter['statics_time'])) {
                list($starttimeStr, $endtimeStr) = explode(' - ', $filter['statics_time']);
            }
            $data = $reserve->where('endtime', '>', $starttimeStr)
                ->where('endtime', '<', $endtimeStr)
                ->where('store_id', $filter['store_id'])
                ->where('user_id', 'not in', [5077, 5079]) //去掉自己和涛哥
                ->where('re_status', 1)
                ->order('id', 'asc')
                ->select();

            $output = [];
            for ($i = 0; $i < 7; $i++) {
                $output[$i] = [
                    'id' => $i,
                    'key' => Carbon::parse('2024-12-23 01:00:00')->addDays($i)->format("l"),
                    'count' => 0,
                    'hour' => 0,
                ];
                $dayOfWeek = Carbon::parse('2024-12-23 01:00:00')->addDays($i)->format("l");

                foreach ($data as $r) {
                    if (Carbon::parse($r->starttime)->format("l") == $dayOfWeek) {
                        $output[$i]['count']++;
                        $output[$i]['hour'] += strtotime($r->endtime) - strtotime($r->starttime);
                    }
                }
            }

            $output = array_map(function ($e) {
                $e['hour'] = ceil($e['hour'] / 3600);
                return $e;
            }, $output);

            $result = array("total" => count($output), "rows" => $output);

            return json($result);


        }

        $stores = \app\admin\model\Store::all();
        $this->view->assign('stores', $stores);
        $this->view->assign('starttime', $starttime);
        $this->view->assign('endtime', $endtime);

        return $this->view->fetch();

    }

    public function storeHourDistribution()
    {
        $starttime = Carbon::now()->startOfMonth()->toDateTimeString();
        $endtime = Carbon::now()->endOfMonth()->toDateTimeString();

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        if ($this->request->isAjax()) {

            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            $filter = $filter ? $filter : [];

            $reserve = new \app\admin\model\Reserve();

            if (isset($filter['statics_time'])) {
                list($starttimeStr, $endtimeStr) = explode(' - ', $filter['statics_time']);
            }
            $data = $reserve->where('endtime', '>', $starttimeStr)
                ->where('endtime', '<', $endtimeStr)
                ->where('store_id', $filter['store_id'])
                ->where('user_id', 'not in', [5077, 5079]) //去掉自己和涛哥
                ->where('re_status', 1)
                ->order('id', 'asc')
                ->select();

            $output = [];
            for ($i = 0; $i < 48; $i++) {
                $output[$i] = [
                    'id' => $i,
                    'key' => Carbon::parse('2023-01-01 00:00:00')->addMinutes(30 * $i)->format("H:i"),
                    'all_count' => 0,
                    'all_fee' => 0,
                    'direct_count' => 0,
                    'direct_fee' => 0,
                    'balance_count' => 0,
                    'balance_fee' => 0,
                    'card_count' => 0,
                    'card_fee' => 0,
                    'dzmt_count' => 0,
                    'dzmt_fee' => 0,
                ];
                $timestart = Carbon::parse('2023-01-01 00:00:00')->addMinutes(30 * $i)->format("H:i");

                foreach ($data as $r) {
                    $s = Carbon::parse($r->starttime)->format("H:i");
                    $e = Carbon::parse($r->endtime)->format("H:i");
                    if ($s <= $timestart and $timestart < $e) {
                        if (1 == $r->pay_way) {
                            $card = \app\admin\model\user\Card::find($r->card_id);
                            if ($card) {
                                $fee = ceil($card->price / $card->total_hour / 2);
                                if (1 == $card->pay_way) {
                                    $output[$i]['dzmt_count']++;
                                    $output[$i]['dzmt_fee'] += $fee;
                                } else if (2 == $card->pay_way) {
                                    $output[$i]['card_count']++;
                                    $output[$i]['card_fee'] += $fee;
                                }
                            }
                        } else if (2 == $r->pay_way) {
                            $rate = (function ($userId) {
                                if ($rate = Cache::get('rate-'.$userId)) {
                                    return $rate;
                                } else {
                                    $countSum = 0;
                                    $countTotal = 0;
                                    $rechanges = \app\admin\model\Transaction::where('type', \app\admin\model\Transaction::TRANS_TYPE_RECHARGE)
                                        ->where('fa_transaction.status', 2)
                                        ->where('fa_transaction.user_id', $userId)
                                        ->select();
                                    foreach ($rechanges as $v) {
                                        $extraInfo = json_decode($v->extra_info, true);
                                        $countSum += $extraInfo['num'];
                                        $countTotal += $extraInfo['num'] + $extraInfo['extra'];
                                    }
                                    if (!$countTotal) {
                                        $rate = 1;
                                    } else {
                                        $rate  = round($countSum / $countTotal, 2);
                                    }
                                    Cache::set('rate-'. $userId, $rate, 3600);
                                    return $rate;
                                }
                            })($r->user_id);

                            $fee = ceil($r->fee / ((strtotime($r->endtime) - strtotime($r->starttime)) / 60 / 30) * $rate);
                            $output[$i]['balance_count']++;
                            $output[$i]['balance_fee'] += $fee;
                        } else if (3 == $r->pay_way) {
                            $fee = ceil($r->fee / ((strtotime($r->endtime) - strtotime($r->starttime)) / 60 / 30));
                            $output[$i]['direct_count']++;
                            $output[$i]['direct_fee'] += $fee;
                        }

                        $output[$i]['all_count']++;
                        $output[$i]['all_fee'] += $fee;
                    }
                }
            }

            $result = array("total" => count($output), "rows" => $output);

            return json($result);


        }

        $stores = \app\admin\model\Store::all();
        $this->view->assign('stores', $stores);
        $this->view->assign('starttime', $starttime);
        $this->view->assign('endtime', $endtime);

        return $this->view->fetch();
    }

    public function rentTimeDistribution()
    {
        $starttime = Carbon::now()->startOfMonth()->toDateTimeString();
        $endtime = Carbon::now()->endOfMonth()->toDateTimeString();


        $this->request->filter(['strip_tags', 'trim']);

        if ($this->request->isAjax()) {

            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            $filter = $filter ? $filter : [];

            $reserve = new \app\admin\model\Reserve();

            if (isset($filter['statics_time'])) {
                list($starttimeStr, $endtimeStr) = explode(' - ', $filter['statics_time']);
            }

            $sql = $reserve->where('endtime', '>', $starttimeStr)
                ->where('user_id', 'not in', [5077, 5079]) //去掉自己和涛哥
                ->where('endtime', '<', $endtimeStr);

            if (isset($filter['store_id']) and !empty($filter['store_id'])) {
                $sql->where('store_id', $filter['store_id']);
            }

            if (isset($filter['re_status']) and !empty($filter['re_status'])) {
                $sql->where('re_status', $filter['re_status']);
            }

            $data = $sql->order('id', 'asc')
                    ->field(['user_id','starttime', 'endtime, re_status'] )
                    ->select();

            $cccc = $this->array_group_by(collection($data)->toArray(), 'user_id');

            $data1 = [];
            foreach ($cccc as $key => $item) {
                $data1[] = [
                    'user_id' => $key,
                    'reserve_count' => count($item),
                    'reserve_min' => ceil(array_reduce($item, function($carry, $item) {
                        return $carry + (Carbon::parse($item['endtime'])->timestamp - Carbon::parse($item['starttime'])->timestamp);
                    }, 0) / 60),
                ];
            }

            $kk = [];
            foreach ($data1 as $item) {
                if (isset($kk[$item['reserve_count']])) {
                    $kk[$item['reserve_count']]['count']++;
                    $kk[$item['reserve_count']]['sum_minute'] += $item['reserve_min'];
                    $kk[$item['reserve_count']]['user_ids'][] = $item['user_id'];
                } else {
                    $userIds = [$item['user_id']];
                    $kk[$item['reserve_count']] = [
                        'count' => 1,
                        'sum_minute' => $item['reserve_min'],
                        'user_ids' => $userIds,
                    ];
                }
            }

            ksort($kk);

            $output = [];
            $i = 1;
            foreach ($kk as $key => $item) {
                $output[] = [
                    'id' => $i,
                    'key' => "${key}次",
                    'count' => $item['count'],
                    'allcount' => $key * $item['count'],
                    'allhour' => floor($item['sum_minute'] / 60),
                    'user_ids_str' => implode(',', $item['user_ids'])
                ];
                $i++;
            }

            $result = array("total" => count($output), "rows" => $output);

            return json($result);


        }

        $stores = \app\admin\model\Store::all();
        $this->view->assign('stores', $stores);

        $this->view->assign('starttime', $starttime);
        $this->view->assign('endtime', $endtime);


        return $this->view->fetch();
    }

    public function userslist()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = User::where($where)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    private function array_group_by($array, $keys)
    {
        if (!is_array($keys) || count($keys) == 1) {
            $key = is_array($keys) ? array_shift($keys) : $keys;

            return array_reduce($array, function ($tmp_result, $item) use ($key) {
                $tmp_result[$item[$key]][] = $item;

                return $tmp_result;
            });
        } else {
            $keys = array_values($keys);

            $result = array_group_by($array, array_shift($keys));

            foreach ($result as $k => $value) {
                $result[$k] = array_group_by($value, $keys);
            }

            return $result;
        }
    }

    public function weixinIncome()
    {
        $starttime = Carbon::now()->startOfMonth()->toDateTimeString();
        $endtime = Carbon::now()->endOfMonth()->toDateTimeString();


        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            $filter = $filter ? $filter : [];

            if (isset($filter['statics_time'])) {
                list($starttime, $endtime) = explode(' - ', $filter['statics_time']);
            }

            $data = Transaction::where('status', 2)
                ->where('createtime', '>', Carbon::parse($starttime)->timestamp)
                ->where('createtime', '<', Carbon::parse($endtime)->timestamp)
                ->select();

            
            $result = [
                'direct_income' => [
                    'name' => '直接购买',
                    'income' => 0,
                    'note' => '',
                ],
                'recharge_income' => [
                    'name' => '充值',
                    'income' => 0,
                    'note' => '',
                ],
                'card_income' => [
                    'name' => '购买储值卡',
                    'income' => 0,
                    'note' => '',
                ],
                'punish_income' => [
                    'name' => '退订支付',
                    'income' => 0,
                    'note' => '',
                ],
                'combo_income' => [
                    'name' => '组合支付',
                    'income' => 0,
                    'note' => '',
                ],
            ];

            foreach ($data as $v) {
                if (Transaction::TRANS_TYPE_DIRECT_BUY == $v->type) {
                    $result['direct_income']['income'] += $v->fee;
                } else if (Transaction::TRANS_TYPE_RECHARGE == $v->type) {
                    $result['recharge_income']['income'] += $v->fee;
                    $result['recharge_income']['note'] .= json_decode($v->extra_info, true)['num'] . '元,';
                } else if (Transaction::TRANS_TYPE_BUY_CARD == $v->type) {
                    $result['card_income']['income'] += $v->fee;
                    $card = \app\admin\model\Card::find($v->extra_info);
                    $result['card_income']['note'] .= $card->card_name . ',';
                } else if (Transaction::TRANS_TYPE_PUNISH == $v->type) {
                    $result['punish_income']['income'] += $v->fee;
                } else if (Transaction::TRANS_TYPE_COMBO == $v->type) {
                    $result['combo_income']['income'] += $v->fee;
                }
            }

            $result = array("total" => count($result), "rows" => array_values($result));

            return json($result);
        }
        $this->view->assign('starttime', $starttime);
        $this->view->assign('endtime', $endtime);
        return $this->view->fetch();
    }
}
